<template>
	<view class="content">
		<uni-notice-bar showClose="false" showIcon class="flyNoticeBar"  single="true" :text="noticeContent"></uni-notice-bar>
		<uni-list :border="true" class="mt20">
		    <uni-list-chat clickable @click="chatVisitor($event,item.visitor_id)" :title="item.username" v-for="item in visitors" :avatar="item.avator" :note="showLastMessage(item.last_message)" :time="formatTime(item.updated_at)" badge-positon="left" :badge-text="showUnreadNum(item.unread_num)"></uni-list-chat>
		</uni-list>
		<view class="flyNotice" v-show="visitors.length==0">
			<uni-icons class="mr-10" type="chatboxes" color="#808080" size="30"></uni-icons>
			暂无在线访客
		</view>
	</view>

</template>

<script>
	import visitorHelper from '../../common/visitors.js';
	import toolsHelper from '../../common/tools.js';
	export default {
		data() {
			return {
				title: 'Hello',
				baseUrl: getApp().globalData.baseUrl,
				wsBaseUrl: getApp().globalData.wsBaseUrl,
				visitors: [],
				token: "",
				timer: null,
				wsOpen: false,
				noticeContent:"通知: 无",
				innerAudioContext:null,
			}
		},
		// 页面显示
		onShow() {
			let _this = this;
			let res = uni.getStorageSync('app');
			console.log(res);
			if (res) {
				this.token = res.token;
			}
			let domainInfo = uni.getStorageSync('domain');
			if (domainInfo) {
				this.baseUrl = domainInfo.domain;
				this.wsBaseUrl=toolsHelper.getWsUrl(domainInfo.domain);
			}
			this.checkAuth();
			this.getOnlineUser();
			this.initPush();
		},
		onLoad() {

		},
		methods: {
			//用户实时上下线
			onlineIntime() {
				var _this = this;
				var timer = null;
				uni.connectSocket({
					url: this.wsBaseUrl + "?token=" + this.token,
				});
				uni.onSocketClose((res) => {
					clearInterval(timer);
					console.log("WebSocket 连接断开");
				});
				uni.onSocketOpen((res) => {
					console.log("WebSocket 连接已打开");;
					let _this = this;
					let mes = {}
					mes.type = "ping";
					mes.data = "";
					timer = setInterval(function() {
						uni.sendSocketMessage({
							data: JSON.stringify(mes),
						});
					}, 5000)

				});
				uni.onSocketMessage((res) => {
					var redata = JSON.parse(res.data);
					switch (redata.type) {
						case "allUsers":
							break;
						case "userOnline":
							_this.addOnlineUser(redata.data);
							toolsHelper.playVoice();
							break;
						case "userOffline":
							_this.removeOfflineUser(redata.data);
							break;
						case "notice":
							break;
						case "message":
							_this.recvMessage(redata.data);
							break;
					}
				});
			},
			getOnlineUser() {
				let _this = this;
				var baseUrl = this.baseUrl;
				uni.request({
					url: baseUrl + '/kefu/onlineVisitors?token=' + _this.token,
					method: 'GET',
					success: function(res) {
						console.log(res);
						if (!res.data.result) {
							return;
						}
						var list=res.data.result;
						for(var i=0;i<list.length;i++){
							list[i].avator=toolsHelper.getImageUrl(list[i].avator,_this.baseUrl);
						}
						_this.visitors = list;
					},
					fail: function(res) {}
				});
			},
			addOnlineUser(retData) {
				retData.avator=toolsHelper.getImageUrl(retData.avator,this.baseUrl);
				this.visitors = visitorHelper.addVisitor(this.visitors,retData);
				this.showNoticeBar(retData.username+"来了");
				//this.showNotice(retData.username+"来了");
			},
			//处理当前在线用户列表
			removeOfflineUser: function(retData) {
				this.visitors = visitorHelper.removeVisitor(this.visitors,retData.visitor_id);
				this.showNoticeBar(retData.name+"离线");
			},
			//点击
			chatVisitor(e, visitorId) {
				uni.navigateTo({
					url: '/pages/index/detail?visitor_id=' + visitorId
				})
			},
			recvMessage(msg) {
				this.visitors = visitorHelper.receiveMessage(this.visitors,msg);
				this.showNoticeBar(msg.name+":"+ msg.content);
				if(msg.is_kefu != "yes"){
					toolsHelper.playVoice();
				}
			},
			initPush(){
				var _this=this;
				//#ifdef APP-PLUS
				    // 页面加载时触发  
					setTimeout(function(){
						if(plus){
							var pinf = plus.push.getClientInfo();
							var cid = pinf.clientid;//客户端标识 
							console.log("app client_id:"+cid);
							_this.registerClient(cid);
							 //监听系统通知栏消息点击事件
							 plus.push.addEventListener('click', function(msg){  
								 console.log("app click");
							     //处理点击消息的业务逻辑代码  
							 }, false);  
							 //监听接收透传消息事件  
							 plus.push.addEventListener('receive', function(msg){  
								 console.log(msg);;
							     //处理透传消息的业务逻辑代码  
								 var options = {cover:false};
								 plus.push.createMessage(msg,"RemoteMSG",options);
							 }, false);
						}
					},4000);
				//#endif
			},
			showNotice(msg){
				// if (uni.getSystemInfoSync().platform == "android") {
				// 	if(window.plus){
				// 		var options = {cover:false};
				// 		plus.push.createMessage(msg,"LocalMSG",options);
				// 	}
				// 	if(uni.vibrate){
				// 		uni.vibrate({
				// 		    success: function () {
				// 		        console.log('success');
				// 		    }
				// 		});
				// 	}
				// }
			},
			showNoticeBar(msg){
				var _this=this;
				_this.noticeContent=msg;
			},
			checkAuth() {
				var _this = this;
				uni.request({
					url: _this.baseUrl + '/uc/v1/refreshToken?token=' + _this.token,
					method: 'POST',
					header: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					success: function(res) {
						var code = res.data.code;
						if (code != 20000) {
							uni.navigateTo({
								url: '/pages/index/login'
							});
						} else {
							uni.setStorageSync("app", {
								token: res.data.result.token,
							});
							_this.onlineIntime();
						}
					}
				});
			},
			registerClient(clientId) {
				let _this = this;
				var baseUrl = this.baseUrl;
				uni.request({
					url: baseUrl + '/kefu/appClient?token='+_this.token,
					data:{client_id:clientId},
					method: 'POST',
					header: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					success: function(res) {
						console.log(res);
					}
				});
			},
			showLastMessage(mes){
				if(mes==""){
					return "无消息";
				}
				return mes
			},
			showUnreadNum(num){
				if(num==0||num=="0"){
					return "dot";
				}
				return num;
			},
			//格式化时间
			formatTime(time) {
				var time = Math.round(new Date(time).getTime()/1000);
				return toolsHelper.beautifyTime(time);
			},
		}
	}
</script>

<style>

</style>
